package com.li.network.lab_4;

import java.util.Map;

public class HttpRequest {
    private String method;
    private String url;
    private String version;
    private Map<String, String> headers;
    private String body;

    public void setMethod(String method) {
        this.method = method;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getVersion() {
        return version;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public String getBody() {
        return body;
    }

    @Override
    public String toString() {
        return "HttpRequest{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", version='" + version + '\'' +
                ", headers=" + headers +
                ", body='" + body + '\'' +
                '}';
    }

    /**
     * 构建请求报文
     * @return
     */
    public byte[] getBytes() {
        String next = "\r\n";
        //请求行
        String stateLine = method + " " + url + " " + version + next;
        //消息头
        StringBuilder headerLine = new StringBuilder();
        headers.forEach((k, v) -> {
            headerLine.append(k + ": " + v).append(next);
        });
        //消息体
        String bodyLine = null;
        if (body != null) {
            bodyLine = next + body;
        }
        //生成字节码
        byte[] stateBytes = stateLine.getBytes();
        byte[] headerBytes = headerLine.toString().getBytes();
        byte[] result;
        if (bodyLine != null) {
            byte[] bodyBytes = bodyLine.getBytes();
            result = new byte[stateBytes.length + headerBytes.length + bodyBytes.length];
            System.arraycopy(stateBytes, 0, result, 0, stateBytes.length);
            System.arraycopy(headerBytes, 0, result, 0, headerBytes.length);
            System.arraycopy(bodyBytes, 0, result, 0, bodyBytes.length);
        } else {
            result = new byte[stateBytes.length + headerBytes.length];
            System.arraycopy(stateBytes, 0, result, 0, stateBytes.length);
            System.arraycopy(headerBytes, 0, result, 0, headerBytes.length);
        }
        return result;
    }
}
